﻿using SimpleSpider.Framework.Model;
using SimpleSpider.Framework.Services.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SimpleSpider.Framework
{
    public abstract class PostWorker
    {
        bool _isStart = false;
        bool isNotData = false;

        ContentService _contentService = null;
        public PostWorker()
        {
            _contentService = new ContentService();

        }

        public abstract void Handler(ContentModel contentModel);


        public void Start()
        {
            if (_isStart) return;
            _isStart = true;

            Task.Factory.StartNew(Work);
        }

        void Work()
        {
            while (true)
            {
                try
                {
                    ContentModel contentModel = Pop();
                    if (contentModel == null)
                    {
                        isNotData = true;
                        continue;
                    }

                    isNotData = false;
                    Handler(contentModel);


                    contentModel.UpdateTime = DateTime.Now;
                    _contentService.Update(contentModel, t => new { t.Status, t.UpdateTime });
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    Thread.Sleep(50);
                }
            }
        }

        ContentModel Pop()
        {
            var contentResult = _contentService.GetFirst(x => x.Status == Reborn.Contracts.State.TaskStatus.WaitingForActivation);
            if (contentResult == null) return contentResult;

            contentResult.UpdateTime = DateTime.Now;
            contentResult.Status = Reborn.Contracts.State.TaskStatus.WaitingToRun;

            _contentService.Update(contentResult, t => new { t.Status, t.UpdateTime });

            return contentResult;
        }
    }
}
